/*
 * @lc app=leetcode.cn id=508 lang=cpp
 *
 * [508] 出现次数最多的子树元素和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> cnt;
    int maxCnt = 0;
    int dfs(TreeNode *root) {
        if (root == NULL) return 0;
        int sum = root->val + dfs(root->left) + dfs(root->right);
        cnt[sum]++;
        maxCnt = max(maxCnt, cnt[sum]);
        return sum;
    }
    vector<int> findFrequentTreeSum(TreeNode *root) {
        dfs(root);
        vector<int> ans;
        for (auto x : cnt) {
            if (x.second == maxCnt) ans.push_back(x.first);
        }
        return ans;
    }
};
// @lc code=end
